const express = require('express');
const jwt = require('jsonwebtoken');
const router = express.Router();
const db = require('../db'); // 数据库连接

const secretKey = "kio"; // 用于JWT加密

// 报修人员登录接口
router.post('/worker/login', (req, res) => {
    const { username, password } = req.body;
    console.log(req.body)
    if (!username || !password) {
        return res.status(400).json({ message: "用户名和密码不能为空" });
    }

    const sql = "SELECT * FROM workers WHERE username = ? AND password = ?";
    db.query(sql, [username, password], (err, results) => {
        if (err) return res.status(500).json({ message: "数据库查询失败" });

        if (results.length === 0) {
            return res.status(401).json({ message: "用户名或密码错误" });
        }

        const worker = results[0];
        const token = jwt.sign(
            { id: worker.id, username: worker.username },
            secretKey,
            { expiresIn: '8h' } // token 有效期 8 小时
        );

        res.json({ message: "登录成功", token });
    });
});

module.exports = router;
